//
//  MakeupColorSelectttView.swift
//  月升
//
//  Created by 拉利法 on 2024/7/12.
//

import UIKit
import SwiftUI

class MakeupColorSelectttView: UIView {
    
    typealias tupleBlock = ((colorName: String, colorLab: String, selectColor: UIColor, rgbColorStr: String, selectTypeIndex: String))->()
    var selectColorBlock: tupleBlock!
    
    private var selectIndex = -1
    private var selectColorIndex = -1
    private var titleL = UILabel()
    private var colorNameL = UILabel()
    private var typeL = UILabel()
    private var dataArr = [String]()
    private var selectColor = UIColor.orange
    private var colorView = ColorPickerView()
    private var colorModelArr = [QIMakeupColorListModel]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(white: 1, alpha: 0.5)
        self.addRoundedCorners(withRadius: 10)
        addUI()
    }
    
    private func addUI() {
        
        titleL = UILabel().then({
            $0.frame = CGRect(x: 0, y: 15, width: self.width, height: 22)
            $0.text = "腮红颜色"
            $0.textColor = Color333333
            $0.textAlignment = .center
            $0.font = FONTBOLD(ofSize: 16)
        })
        self.addSubview(titleL)
        
        colorView = ColorPickerView(frame: CGRect(x: self.width / 2 - 55, y: titleL.bottom + 10, width: 110, height: 110))
        colorView.setPickerStyle(.pie) { color in
//            self.backgroundColor = color
            self.selectColor = color!
            self.getColorArr()
        }
        self.addSubview(colorView)
        
        colorNameL = UILabel().then({
            $0.frame = CGRect(x: 0, y: colorView.bottom + 5, width: self.width, height: 17)
            $0.text = ""
            $0.textColor = Color333333
            $0.textAlignment = .center
            $0.font = FONT(ofSize: 12)
        })
        self.addSubview(colorNameL)
        
        typeL = UILabel().then({
            $0.frame = CGRect(x: 0, y: colorNameL.bottom + 12, width: self.width, height: 22)
            $0.text = "腮红形状"
            $0.textColor = Color333333
            $0.textAlignment = .center
            $0.font = FONTBOLD(ofSize: 16)
        })
        self.addSubview(typeL)
        
        collectionView.frame = CGRect(x: 10, y: typeL.bottom + 10, width: self.width - 20, height: 65)
        self.addSubview(collectionView)
        
        let confirmBtn = UIButton().then {
            $0.frame = CGRect(x: 50, y: self.height - 40, width: self.width - 100, height: 30)
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("确定", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addTarget(self, action: #selector(confirmBtnClick), for: .touchUpInside)
        }
        self.addSubview(confirmBtn)
        
    }
    
    var typeStr = "" {
        didSet {
            titleL.text = "\(typeStr)颜色"
            if typeStr == "口红" {
                typeL.isHidden = true
                selectIndex = -1
                collectionView.isHidden = true
            } else {
                typeL.text = "\(typeStr)形状"
                if typeStr == "眼影" {
                    collectionView.tag = 4
                    dataArr = ["柔美", "猫眼", "古风", "日常", "欧美", "烟熏", "狐媚", "落日"]
                } else if typeStr == "腮红" {
                    collectionView.tag = 3
                    dataArr = ["纤窄型", "细长型", "宽长型", "连鼻型", "圆小型"]
                }
                collectionView.reloadData()
            }
        }
    }
    
    private func getColorArr() {
        let url = "http://124.222.206.164:9200/develop_shade_clustering"
        var param = ["rgb_value_string": getRGB(from: selectColor)]
        if typeStr == "眼影" {
            param["cosmetics_type"] = "eye_shadow"
        } else if typeStr == "腮红" {
            param["cosmetics_type"] = "blush"
        } else if typeStr == "口红" {
            param["cosmetics_type"] = "lipstick"
        }
        QINetworkManager.requestJson(urlStr: url, parameters: param, isJson: true) { json in
            print(json)
            self.colorModelArr = json.arrayObject?.kj.modelArray(QIMakeupColorListModel.self) ?? [QIMakeupColorListModel]()
            self.colorView.isHidden = true
            self.selectColorIndex = Int(self.colorModelArr.count / 4)
            
            let colorView = ColorDiscView(frame: CGRect(x: self.width / 2 - 55, y: self.titleL.bottom + 10, width: 110, height: 110))
            colorView.colorModelArr = self.colorModelArr
            colorView.addRoundedCorners(withRadius: 55)
            colorView.selectIndex = { i in
                let model = self.colorModelArr[i]
                self.selectColorIndex = i
                self.colorNameL.text = "\(model.brand) \(model.shade)"
            }
            self.addSubview(colorView)
        }
    }
    
    @objc private func confirmBtnClick() {
        guard selectColorIndex >= 0 else {
            ShowHUD(str: "请选择\(typeStr)颜色")
            return
        }
        guard selectIndex >= 0 || typeStr == "口红" else {
            ShowHUD(str: "请选择\(typeStr)形状")
            return
        }
        if selectColorBlock != nil {
            let model = colorModelArr[selectColorIndex]
            let colorArr = model.color_rgb.first ?? [0, 0, 0]
            let color = UIColor(red: colorArr[0] / 255, green: colorArr[1] / 255, blue: colorArr[2] / 255, alpha: 1)
            selectColorBlock(("\(model.brand) \(model.shade)", typeStr == "口红" ? "" : dataArr[selectIndex], selectColor: color, rgbColorStr: "\(Int(colorArr[0])),\(Int(colorArr[1])),\(Int(colorArr[2])),\(typeStr == "口红" ? 0 : selectIndex)", selectTypeIndex: "\(selectIndex)"))
            QINPopUpTool.sharedInstance().clear()
        }
    }
    
    func getRGB(from color: UIColor) -> String {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        
        let colorRef = color.cgColor
        let components = colorRef.components
        
        if let components = components {
            red = components[0] * 255
            green = components[1] * 255
            blue = components[2] * 255
            alpha = components[3]
        }
        
        return "\(Int(red)),\(Int(green)),\(Int(blue))"
    }
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
//        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(MakeupColorSelectCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        return collectionView
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


extension MakeupColorSelectttView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellW = Int(self.width) / collectionView.tag - 15
        return CGSize(width: cellW, height: 26)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MakeupColorSelectCell
        cell.titleStr = dataArr[indexPath.row]
        cell.isSelect = indexPath.row == selectIndex
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectIndex = indexPath.row
        collectionView.reloadData()
    }
    
}



class MakeupColorSelectCell: UICollectionViewCell {
    
    private var titleL = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addUI()
    }
    
    private func addUI() {
        titleL = UILabel().then({
            $0.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
            $0.text = ""
            $0.textColor = Color333333
            $0.textAlignment = .center
            $0.font = FONT(ofSize: 14)
            $0.addRoundedCorners(withRadius: 11)
        })
        self.addSubview(titleL)
    }
    
    var titleStr = "" {
        didSet {
            titleL.text = titleStr
        }
    }
    var isSelect = false {
        didSet {
            if isSelect {
                titleL.backgroundColor = MainColor
                titleL.textColor = .white
            } else {
                titleL.backgroundColor = .clear
                titleL.textColor = Color333333
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}




class ColorDiscView: UIView {
    
    var selectIndex: intBlock!
    private var linView = UIImageView()
    private var colorView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.backgroundColor = .white
        addUI()
    }
    
    private func addUI() {
        
        colorView.frame = CGRect(x: 3, y: 3, width: 104, height: 104)
        colorView.backgroundColor = .white
        colorView.addRoundedCorners(withRadius: 52)
        self.addSubview(colorView)
        
//        let colorCount = 30
//        for i in 0..<colorCount {
//            let interval: CGFloat = .pi * 2 / CGFloat(colorCount)
//            let start = (-.pi / 2) + (interval * CGFloat(i))
//            let end = start + 0.2
//            let layer = CAShapeLayer()
//            layer.path = UIBezierPath(arcCenter: CGPoint(x: 52, y: 52), radius: 52, startAngle:start, endAngle: end, clockwise: true).cgPath
//            layer.strokeColor = RandomColor().cgColor
//            layer.fillColor = UIColor.clear.cgColor
//            layer.lineWidth = 104
//            colorView.layer.addSublayer(layer)
//            
//        }
        
        
        linView.frame = CGRect(x: 52, y: 0, width: 6, height: 55)
        linView.image = UIImage(named: "色盘指针")
        self.addSubview(linView)
        
    }
    
    
    var colorModelArr = [QIMakeupColorListModel]() {
        didSet {
            let colorCount = colorModelArr.count
            for i in 0..<colorCount {
                let model = colorModelArr[i]
                let rgbArr = model.color_rgb.first ?? [0, 0, 0]
                
                let interval: CGFloat = .pi * 2 / CGFloat(colorCount)
                let start = (interval * CGFloat(i)) + (-.pi / 1)
                let end = start + 0.2
                let layer = CAShapeLayer()
                layer.path = UIBezierPath(arcCenter: CGPoint(x: 52, y: 52), radius: 52, startAngle:start, endAngle: end, clockwise: true).cgPath
                layer.strokeColor = UIColor(red: rgbArr[0] / 255, green: rgbArr[1] / 255, blue: rgbArr[2] / 255, alpha: 1).cgColor//RandomColor().cgColor
                layer.fillColor = UIColor.clear.cgColor
                layer.lineWidth = 104
                colorView.layer.addSublayer(layer)
                
            }
        }
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: self)
            print("开始触摸：x = \(location.x), y = \(location.y)")
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: self)
//            print("移动触摸：x = \(location.x), y = \(location.y)")
            
            
            let centerPoint = CGPoint(x: 55, y: 55)
            let currentPoint = location
            let angleBetweenPoints = angle(from: centerPoint, to: currentPoint)
            
            linView.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
            linView.layer.position = CGPoint(x: 55, y: 55)
            linView.transform = CGAffineTransform(rotationAngle: angleBetweenPoints + CGFloat.pi / 2)
            
            
//            let angle = angleBetweenPoints1(center: CGPoint(x: 55, y: 55), point1: CGPoint(x: 0, y: 55), point2: location)
//            print(angle)
//            let degrees = angle * 180 / CGFloat.pi + 360
//            print(degrees)
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: self)
            print("结束触摸：x = \(location.x), y = \(location.y)")
            
            let angle = angleBetweenPoints1(center: CGPoint(x: 55, y: 55), point1: CGPoint(x: 0, y: 55), point2: location)
            let degrees = angle * 180 / CGFloat.pi + 360
            let newAngle = angle + .pi * 2
            let interval: CGFloat = .pi * 2 / CGFloat(colorModelArr.count)
            let index = Int(newAngle / interval)
            print(index)
            
            if selectIndex != nil {
                selectIndex(index)
            }
        }
    }
    
    
    func angle(from startPoint: CGPoint, to endPoint: CGPoint) -> CGFloat {
        return atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x)
    }
    
    func angleBetweenPoints1(center: CGPoint, point1: CGPoint, point2: CGPoint) -> CGFloat {
        let deltaX1 = point1.x - center.x
        let deltaY1 = point1.y - center.y
        let deltaX2 = point2.x - center.x
        let deltaY2 = point2.y - center.y
     
        let angle1 = atan2(deltaY1, deltaX1)
        let angle2 = atan2(deltaY2, deltaX2)
     
        let angle = angle2 - angle1
     
        return angle
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
